package com.louis.resource;

import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author XRY
 * @date 2023年06月28日18:40
 */
//访问类路劲下的资源
public class ClassPathResourceDemo {
    public static void loadClassPathResource(String url){
        //创建对象
        ClassPathResource classPathResource = new ClassPathResource(url);
        System.out.println("classPathResource.getFilename() = " + classPathResource.getFilename());
        System.out.println("classPathResource.getDescription() = " + classPathResource.getDescription());
        //获取文件内容
        try {
            InputStream inputStream = classPathResource.getInputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while((len = inputStream.read(b)) != -1){
                System.out.println(new String(b, 0, len));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        //是相对路径，可以放在resources下
        loadClassPathResource("louis.txt");
        /*
        * classPathResource.getFilename() = louis.txt
          classPathResource.getDescription() = class path resource [louis.txt]
          Hi,louis
        * */
    }
}
